// 1. 留言列表

function loadData() {
  const $list = $('.list');

  $list.text('Loading....');

  $.ajax({
    type: 'GET',
    url: 'http://82.156.8.100:5000/messages',
    data: {
      _sort: 'id',
      _order: 'desc'
    },
    success: function (data) {
      $list.text('');
      $('.title').text('')
      $('.title').text(`最新留言(${data.length})条`)

      const arr = [];
      console.log(data);
      data?.forEach(item => {
        const message = `
          <div class="message">
            <div class="box">
              <img src="${item.avatar}" alt="" />
              <div class="item">
                <div class="user">${item.user}</div>
                <div class="content">${item.content}</div>
              </div>
            </div>
            <span class="time">${dayjs().to(dayjs(item.time))}</span>
            <span data-id="${item.id}" class="close">X</span>
          </div>
        `;
        arr.push(message);
      })
      $list.append(arr.join(''));

      // 3 删除留言
      $('.close').on('click', function () {
        if (!confirm('确定删除该留言么？')) return false;
        const id = $(this).data('id');
        $.ajax({
          type: 'DELETE',
          url: `http://82.156.8.100:5000/messages/${id}`,
          success: function (data) {
            $(this).parent().remove();
          }.bind(this),
          error: function (jqXHR, textStatus, errorThrown) {
            console.log('请求出错' + errorThrown);
          }
        })
      });
    },
    error: function (jqXHR, textStatus, errorThrown) {
      console.log('请求出错' + errorThrown);
    }
  });
}

loadData()

// 2. 发布留言
const $user = $('#user');
const $content = $('#content');

const $btn = $('.btn');

$btn.on('click', function () {
  const user = $user.val();
  const content = $content.val();
  const time = new Date();
  const avatar = 'images/2.webp';

  $.ajax({
    type: 'POST',
    url: 'http://82.156.8.100:5000/messages',
    data: {
      user: user,
      content: content,
      time: time,
      avatar: avatar
    },
    success: function (data) {
      loadData()
    },
    error: function (jqXHR, textStatus, errorThrown) {
      console.log('请求出错' + errorThrown);
    }
  });
});


// 4. 天气预报

$.ajax({
  type: 'GET',
  url: 'http://82.156.8.100:5000/weather',
  success: function (data) {
    const result = data.result
    const str = `${result.location.province} ${result.location.city} ${result.now.text}${result.now.wind_dir} ${result.now.wind_class}`
    $('.weather').text(str)
  },
  err: function (jqXHR, textStatus, errorThrown) {
    console.log('请求出错' + errorThrown);
  }
})